package server

import (
	"os"
	"path/filepath"
	"stforum/databases"
	"stforum/global"
	"stforum/sthelp"

	"github.com/gin-gonic/gin"
)

func Start() {
	TimeLimiter := NewServerTimeLimiter()
	global.MainServer = gin.Default()
	global.MainServer.Use(TimeLimiter.Limit())

	//标记文件不存在，进行初始化
	if !sthelp.PathExists("st.lock") {
		global.Logger.Info("检测到尚未初始化或者误删.lock文件")
		global.Logger.Info("正在启动初始化服务器...")
		StartInitServer()
		return
	}

	start_ok, err_data := databases.StartBaseDataBases()
	if !start_ok {
		global.Logger.Error("数据库启动失败！", "失败原因：", err_data.Error())
		os.Exit(1)
	}

	global.AdminServer = gin.Default()
	global.AdminServer.Use(TimeLimiter.Limit())
	//初始化完成，进行路由绑定和服务器启动
	Info, err := databases.GetBaseSettingInfo()
	wd, _ := os.Getwd()
	if err != nil {
		global.Logger.Error("读取数据库数据失败！", err.Error())
		os.Exit(1)
	}
	BindStaticRouter(filepath.Join(wd, "data", "admin"), global.AdminServer)
	go func() {
		global.Logger.Info("正在启动Admin Server:", Info.AdminPort)
		err_start := global.AdminServer.Run("0.0.0.0:" + Info.AdminPort)
		if err_start != nil {
			global.Logger.Error("启动admin服务器失败", err_start.Error())
			os.Exit(1)
		}
	}()

	//index
	BindStaticRouter(filepath.Join(wd, "data", "index"), global.MainServer)
	global.Logger.Info("正在启动Index Server:", Info.Port)
	err_start := global.MainServer.Run("0.0.0.0:" + Info.Port)
	if err_start != nil {
		global.Logger.Error("启动Index Server失败", err.Error())
		os.Exit(1)
	}
}
